package com.licode.codekit;

import com.intellij.ide.IdeView;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.licode.codekit.buildprj.GenerateCodeUI;
import com.licode.codekit.buildprj.GenerateEntityUI;
import com.licode.codekit.db.AssembledDb;
import com.licode.codekit.db.EntityBuilder;
import com.licode.codekit.db.GenerateCtx;
import com.licode.codekit.db.LiSysConfig;
import com.licode.codekit.utils.DbDriverDlUtil;
import com.licode.codekit.utils.PluginUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;

/**
 * @author licode
 */
public class BuildEntityKit extends AnAction {

    @Override
    public void update(@NotNull AnActionEvent e) {
        ActionEventUtil.handleDirEvent(e);
        super.update(e);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        IdeView ideView = e.getRequiredData(LangDataKeys.IDE_VIEW);
        // 选择的文件夹
        PsiDirectory psiDirectory = ideView.getOrChooseDirectory();
        assert psiDirectory != null;
        // 选择的项目
        Project project = psiDirectory.getProject();
        String currPrj = psiDirectory.getVirtualFile().getPath();

        GenerateEntityUI autoEntityUI = new GenerateEntityUI(project, currPrj);
        autoEntityUI.setResizable(true);
        PluginUtil.getPluginDir();
        handleMysqlDriver();

        autoEntityUI.show();
    }

    private void handleMysqlDriver() {
        if (!AssembledDb.dbDriverValid()) {
            String driverPath = LiSysConfig.getInstance().getDbDriver();
            AssembledDb.initDbClassloader(driverPath, false);
            if (!AssembledDb.dbDriverValid()) {
                DbDriverDlUtil.downMysqlFromResource(driverPath, false);
                AssembledDb.initDbClassloader(driverPath, false);
            }
        }
    }
}
